// 初始项目把所有的package.json中的file字段更换为版本号
var fs = require("fs")
var join = require('path').join;
const jsonFile = require('jsonfile')

// 从根目录开始读取，识别package.josn文件
let jsonFiles =  getJsonFiles("./");
let version = '1.1.5'
function getJsonFiles(jsonPath) {
    let jsonFiles = [];
    function findJsonFile(path) {
        let files = fs.readdirSync(path);
        files.forEach(function (item, index) {
            let fPath = join(path, item);
            let stat = fs.statSync(fPath);
            if (stat.isDirectory() === true) {
                findJsonFile(fPath);
            }
            if (stat.isFile() === true) {
                if(fPath.indexOf('package.json') > -1 && fPath.indexOf('node_modules') === -1) {
                    jsonFiles.push(fPath);
                }
            }
        });
    }
    findJsonFile(jsonPath);
    return jsonFiles
}

function modifyAppJSON(path) {
    jsonFile
        .readFile(path)
        .then(appConfig => {
            let dependencies = appConfig['dependencies']
            if (dependencies) {
                for (let key in dependencies) {
                    if (key.indexOf('@liangshaojie') > -1) {
                        dependencies[key] = version
                    }
                }
            }
            if(appConfig.publishConfig){
                appConfig.publishConfig.access = "public"
            }
            appConfig.version = version 
            appConfig.dependencies = dependencies
            jsonFile.writeFile(path, appConfig, {
                spaces: 4
            }).catch(error => console.error(error))
        })
        .catch(error => console.error(error))
}

// 遍历package.json文件批量更给版本号
jsonFiles.forEach(path => {
    modifyAppJSON(path)
})



